import { EventClass } from "@lib/alen-helper/base/baseClass";
import { AppAisle } from "@lib/alen-helper/base/appAisle/";
import { MainSDK } from "./main.sdk";
import { concatMap, from, map, Subscription } from "rxjs";


export namespace ApplicationSDK {
    export interface Options {
        appid: string,
        aisle: AppAisle<MainSDK.CmdData>,
    }
}

export class ApplicationSDK extends EventClass<{
    close: {
        preventClose: boolean,
    },
    destroy_all_window: null,
}> {
    constructor(
        public readonly options: ApplicationSDK.Options,
        BaseOptions?: Partial<EventClass.BaseOptions>
    ) {
        super('Application', BaseOptions);
    }

    get appid() {
        return this.options.appid;
    }

    get aisle() {
        return this.options.aisle;
    }

    private _handlers: Partial<AppAisle.CmdHandlers<Runtime.Controller.ComonnCmdData_Client>> = {
        app_event_close: (data, aisle) => {
            return this.triggerEventEnd('close', data.data.param);
        },
        app_event_destroy_all_window: (data, aisle) => {
            return this.triggerEventEnd('destroy_all_window', null).pipe(map(() => null));
        },
    }

    private _setHandlers() {
        this.aisle.setHandler<Runtime.Controller.ComonnCmdData_Client>(this._handlers);
    }
    private _subs: Subscription | null = null;
    private _unSub() {
        if (this._subs) this._subs.unsubscribe();
        this._subs = null;
    }
    private _sub() {
        this._unSub();
        this._subs = this.event('destroy_all_window')
            .subscribe(() => {
                this._log.info(`app => destroy_all_window `);
            });
    }

    close() {
        return this.aisle.cmd('app_close', { appid: this.appid });
    }

    init() {
        this._setHandlers();
        this._sub();
    }
}